//import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from './routes'
import { getUserToken } from '@/utils/token'
import { resetPushOrReplace } from '@/utils/func'
import store from '@/store'

//Vue.use(VueRouter)

const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = resetPushOrReplace(originPush)
VueRouter.prototype.replace = resetPushOrReplace(originReplace)

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior() {
    return { x: 0, y: 0 }
  }
})
//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) document.title = to.meta.title

  if (getUserToken()) {
    //已登录
    if (to.path === '/login' || to.path === '/register') {
      next(false)
    } else {
      const name = store.state.login.userInfo.loginName
      if (name) {
        next()
      } else {
        try {
          await store.dispatch('login/getUserInfo')
          next()
        } catch (error) {
          await store.dispatch('login/logOut')
          next('/login')
        }
      }
    }
  } else {
    //未登录
    const path = to.path //获取路径
    //判断路径是否为下面条件
    if (path.indexOf('/trade') !== -1 || path.indexOf('/pay') !== -1 || path.indexOf('/center') !== -1) {
      next('/login?redirect=' + path)//路由放行到登录页
    } else {
      next() //全部放行
    }

  }
})

export default router;